package com.hk.app.utils;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by Antinomy on 17/1/20.
 * <p>
 * ref : https://en.wikipedia.org/wiki/Software_versioning
 */
public class UniqueVersion {

    private String orgiVersionText = null;
    private Integer major = 0;
    private Integer minor = 0;
    private Integer maintenance = 0;

    public UniqueVersion(String versionStr) throws Exception {
        this.orgiVersionText =versionStr;

        if (StringUtils.isBlank(versionStr))
            throw new Exception("版本号不能为空");

        String[] vers = versionStr.split("\\.");

        try {
            if (vers.length == 1) {
                major = Integer.valueOf(versionStr);
                return;
            }

            if (vers.length == 2) {
                major = Integer.valueOf(vers[0]);
                minor = Integer.valueOf(vers[1]);
                return;
            }

            if (vers.length == 3) {
                major = Integer.valueOf(vers[0]);
                minor = Integer.valueOf(vers[1]);
                maintenance = Integer.valueOf(vers[2]);
                return;
            }
        } catch (NumberFormatException ex) {
            throw getValidateException(versionStr);
        }

        throw getValidateException(versionStr);
    }


    public Integer getMajor() {
        return major;
    }


    public Integer getMinor() {
        return minor;
    }

    public Integer getMaintenance() {
        return maintenance;
    }

    private Exception getValidateException(String versionStr) {
        return new Exception("版本号不是标准格式:" + versionStr);
    }

    public boolean isGreaterThan(UniqueVersion otherVersion) {
        if (this.major < otherVersion.getMajor())
            return false;

        if (this.major > otherVersion.getMajor())
            return true;

        if (this.minor < otherVersion.getMinor())
            return false;

        if (this.minor > otherVersion.getMinor())
            return true;

        if (this.maintenance > otherVersion.getMaintenance())
            return true;

        if (this.maintenance <= otherVersion.getMaintenance())
            return false;

        if(isEquals(otherVersion))
            return false;

        return false;
    }

    public boolean isEquals(UniqueVersion otherVersion) {
        return this.major.equals(otherVersion.getMajor())
                && this.minor.equals(otherVersion.getMinor())
                && this.maintenance .equals(otherVersion.getMaintenance());
    }

    public boolean isEqualLessThan(UniqueVersion otherVersion) {
        return !isGreaterThan(otherVersion);
    }

    public boolean isEqualGreaterThan(UniqueVersion otherVersion) {
        return isGreaterThan(otherVersion) || isEquals(otherVersion);
    }


    public String getOrgiVersionText() {
        return orgiVersionText;
    }
}
